//
//  CantripDocumentController.m
//  Cantrip
//
//  Created by James Callender on Tue May 07 2002.
//  Copyright (c) 2001 James Callender. All rights reserved.
//

#import "CantripDocumentController.h"

@implementation CantripDocumentController

- (id)init
{
    if (self = [super init]) {
	heartBeat = [[NSTimer scheduledTimerWithTimeInterval:1 
	    target:self selector:@selector(beat:) userInfo:nil repeats:YES] retain];
    }

    return self;
}

- (void)dealloc
{
    [heartBeat invalidate];
    [heartBeat release];
    [super dealloc];
}

- (id)makeUntitledDocumentOfType:(NSString*)type
{
    id doc = [super makeUntitledDocumentOfType:type];
    NSEnumerator *e = [[[CantripWorldSettingsController sharedInstance] settingsModules] objectEnumerator];
    NSObject<CantripSettingsModuleProtocol> *module;

    while (module = [e nextObject]) {
	if ([module respondsToSelector:@selector(defaultWorldProperties)]) {
	    [[doc worldData] addEntriesFromDictionary:[module defaultWorldProperties]];
	}
    }
        
    [[CantripPluginManager sharedPluginManager]
	    makePluginsPerformSelector:@selector(applicationDidCreateUntitledWorld:) withObject:doc];

    return doc;
}

- (id)openDocumentWithContentsOfFile:(NSString *)fileName display:(BOOL)display
{
    id doc = [super openDocumentWithContentsOfFile:fileName display:display];

    [[CantripPluginManager sharedPluginManager]
	    makePluginsPerformSelector:@selector(applicationDidLoadWorld:) withObject:doc];

    return doc;
}

- (void)removeDocument:(NSDocument *)document
{
    [super removeDocument:document];
}

- (id)activeDocument
{
    NSDocument *activeDocument;
    activeDocument = [super currentDocument];

    if (!activeDocument) {
	activeDocument = [[[NSApp mainWindow] windowController] document];
    }

    if (!activeDocument) {
	NSEnumerator *e;
	NSWindow *w;
	e = [[NSApp windows] objectEnumerator];

	while (w = [e nextObject]) {
	    if (![w isMiniaturized]) {	
		activeDocument = [self documentForWindow:w];
		if (activeDocument) break;
	    }
	}
    }

    return activeDocument;
}

- (id)documentForWindow:(NSWindow *)window
{
    id document = [super documentForWindow:window];
    if (!document) {
	document = [[window windowController] document];
    }

    return document;
}


- (void)beat:(id)sender
{
    NSEnumerator *e;
    CantripWorldDocument *world;

    e = [[self documents] objectEnumerator];

    while (world = [e nextObject]) {
	[world timerBeat:sender];
    }
}


@end
